package 链表;

public class Demo05 {
    static class Solution {
        public ListNode reverseBetween(ListNode head, int left, int right) {
            ListNode newHead = new ListNode(0);
            ListNode cur = head;
            ListNode pre = null;
            ListNode nextNode = null;
            int count = left-1;
            while(count > 0){
                if(count == 1){
                    pre = cur;
                }
                cur = cur.next;
                count--;
            }

            count = right - left+1;
            while(count-- >0){
                ListNode next = newHead.next;
                newHead.next = cur;
                cur = cur.next;
                newHead.next.next = next;
            }
            nextNode = cur;

            cur = newHead;
            while(cur.next != null){
                cur = cur.next;
            }
            cur.next = nextNode;

            if(pre != null){
                pre.next = newHead.next;
                return head;
            }else{
                return newHead.next;
            }
        }
    }
}
